package com.yanyuan.mybaits.config.xml;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.LinkedList;
import java.util.List;

/**
 * @Description xml解析器
 * @Author yanyuan
 * @Date 14:42 2020/3/18
 * @Version 1.0
 **/
@Slf4j
public class XmlBuilder {

    XStream xstream = new XStream(new StaxDriver());

    public List<Mapper> build() {
        List<Mapper> mapperList = new LinkedList<>();
        //使用注解方式
        xstream.autodetectAnnotations(true);
        xstream.processAnnotations(Mapper.class);
//        List<Resource> resourceList = new LinkedList();
//        resourceList.add(new ClassPathResource("mapper/MessageMapper.xml"));
//        resourceList.add(new ClassPathResource("mapper/UserMapper.xml"));
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources =  resolver.getResources("mapper/*.xml");
            log.info("resource length {} ", resources.length);
            for (Resource resource : resources){
                Mapper mapper = (Mapper) xstream.fromXML(resource.getFile());
                mapperList.add(mapper);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(MessageFormat.format(" parse xml fail , error msg {0} ", e.getMessage()));
        }
        log.info("mapperList {} ", mapperList);
        return mapperList;
    }

}
